package cn.kongnannan.circularavatar;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.app.Context;
import ohos.media.image.PixelMap;

import java.util.ArrayList;

/**
 * CircularImageView
 */
public class CircularImageView extends Component implements Component.DrawTask {
    /**
     * viewWidth
     */
    protected int viewWidth;

    /**
     * viewHeight
     */
    protected int viewHeight;
    /**
     * bmps
     */
    protected ArrayList<PixelMap> bmps;

    /**
     * CircularImageView
     *
     * @param context Context
     */
    public CircularImageView(Context context) {
        super(context);
        addDrawTask(this);
    }

    /**
     * CircularImageView
     *
     * @param context Context
     * @param attrs AttrSet
     */
    public CircularImageView(Context context, AttrSet attrs) {
        super(context, attrs);
        addDrawTask(this);
    }

    /**
     * CircularImageView
     *
     * @param context Context
     * @param attrs AttrSet
     * @param defStyle integer
     */
    public CircularImageView(Context context, AttrSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        addDrawTask(this);
    }

    /**
     * onMeasure
     *
     * @param widthMeasureSpec integer
     * @param heightMeasureSpec integer
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getEstimatedWidth();
        int height = getEstimatedHeight();
        int dimen = Math.min(width, height);
        setEstimatedSize(dimen, dimen);
    }

    /**
     * setImageBitmaps
     *
     * @param bitmaps
     */
    public void setImageBitmaps(ArrayList<PixelMap> bitmaps) {
        if (bitmaps == null)
            throw new IllegalArgumentException("bitmaps can not be Null");
        if (bitmaps.size() > JoinLayout.max())
            throw new IllegalArgumentException("bitmaps size can not be greater than "
                    + JoinLayout.max());
            this.bmps = bitmaps;
            invalidate();
    }

    /**
     * onSizeChanged
     *
     * @param w width
     * @param h height
     * @param oldw oldwidth
     * @param oldh oldheight
     */
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        viewWidth = w;
        viewHeight = h;
        viewWidth = viewHeight = Math.min(w, h);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        onMeasure(component.getEstimatedWidth(),component.getEstimatedHeight());
        onSizeChanged(getWidth(),getHeight(),Constants.ZERO_NUM_CONST,Constants.ZERO_NUM_CONST);
        if (viewWidth > Constants.ZERO_NUM_CONST && viewHeight > Constants.ZERO_NUM_CONST) {
            JoinBitmaps.join(canvas, viewWidth, bmps, Constants.DECIMAL_FIFTEEN_NUM_CONST);
        }
    }
}
